import 'dart:convert';

import 'package:flutter/material.dart';
import 'package:scoped_model/scoped_model.dart';
import 'package:flutter_staggered_grid_view/flutter_staggered_grid_view.dart';
import 'package:flutter_spinkit/flutter_spinkit.dart';

import 'package:flutter_popcorntime/routers/routers.dart';
import 'package:flutter_popcorntime/widgets/rating_star_widget.dart';
import 'package:flutter_popcorntime/models/json/video_data_json.dart';
import 'package:flutter_popcorntime/models/video_model.dart';
import 'package:flutter_popcorntime/models/video_item.dart';
import 'package:flutter_popcorntime/widgets/cached_image_widget.dart';

class VideoListWidget extends StatefulWidget {
  final String tabName;

  VideoListWidget(this.tabName);

  @override
  _VideoListWidgetState createState() => _VideoListWidgetState();
}

class _VideoListWidgetState extends State<VideoListWidget> {
  @override
  void initState() {
    super.initState();
  }

  Future<void> _onRefresh() async {
    await VideoModel.of(context).refreshList(widget.tabName, force: true);
  }

  @override
  Widget build(BuildContext context) {
    print("VideoDetail ${widget.tabName} build");
    VideoModel model = VideoModel.of(context);
    List<VideoItem>? videoItemList = model.videoList(widget.tabName);
    return model.statusModel == StatusModel.loading || videoItemList == null
        ? SpinKitFadingFour(color: Colors.lightBlue)
        : videoItemList.isEmpty
            ? GestureDetector(
                child: Center(
                  child: Text(
                    "网络不给力，点击屏幕重试",
                    textScaleFactor: 1.5,
                    style: TextStyle(color: Colors.grey),
                  ),
                ),
                onTap: () {
                  _onRefresh();
                },
              )
            : RefreshIndicator(
                onRefresh: _onRefresh,
                child: ScopedModelDescendant<VideoModel>(
                  builder: (context, child, model) {
                    return StaggeredGridView.countBuilder(
                      crossAxisCount: 4,
                      itemCount: videoItemList.length,
                      itemBuilder: (context, index) =>
                          _buildVideoDetailItemWidget(model, index),
                      staggeredTileBuilder: (index) {
                        return StaggeredTile.count(2, 3);
                      },
                      mainAxisSpacing: 15.0,
                      crossAxisSpacing: 15.0,
                      physics: BouncingScrollPhysics(),
                      padding: EdgeInsets.only(top: 4.0, bottom: 4.0),
                    );
                  },
                ),
              );
  }

  Widget _buildVideoDetailItemWidget(VideoModel model, int index) {
    // print("VideoDetailItem ${widget.tabName} $index build");
    List<VideoItem>? videoItemList = model.videoList(widget.tabName);
    VideoItem videoItem = videoItemList![index];
    VideoData videoData = videoItem.videoData;
    return Stack(
      children: <Widget>[
        Positioned.fill(
          bottom: 40,
          child: GestureDetector(
            child: Container(
              color: Colors.white,
              child: CachedImageWidget(
                imageUrl: videoData.posterBig ?? "",
                fit: BoxFit.fitWidth,
              ),
            ),
            onTap: () {
              print("Tap Movie $index");
              final String videoDataJson = json.encode(videoData.toJson());
              Routers().router.navigateTo(context,
                  "${Routers.videoDetailPage}?data=${Uri.encodeComponent(videoDataJson)}");
            },
          ),
        ),
        Positioned(
          left: 0,
          right: 0,
          bottom: -5,
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: <Widget>[
              Container(
                height: 20,
                child: Text(
                  videoData.title ?? "",
                  overflow: TextOverflow.ellipsis,
                  textAlign: TextAlign.left,
                  maxLines: 1,
                  style: TextStyle(
                    color: Colors.white,
                    fontSize: 13,
                    fontWeight: FontWeight.bold,
                  ),
                ),
              ),
              Container(
                height: 20,
                child: Text(
                  videoData.year?.toString() ?? "",
                  overflow: TextOverflow.ellipsis,
                  textAlign: TextAlign.left,
                  maxLines: 1,
                  style: TextStyle(
                    color: Colors.white30,
                    fontSize: 13,
                  ),
                ),
              ),
            ],
          ),
        ),
        Positioned(
          top: 0,
          right: 0,
          child: GestureDetector(
            child: Container(
              width: 50,
              height: 40,
              margin: EdgeInsets.only(right: 9),
              child: Icon(
                videoItem.favorite ? Icons.favorite : Icons.favorite_border,
                color: videoItem.favorite ? Colors.red : Colors.white,
              ),
            ),
            onTap: () {
              print("Tap favorite $index");
              model.favorite(videoItem, !videoItem.favorite);
            },
          ),
        ),
        Positioned(
          top: 0,
          left: 0,
          child: GestureDetector(
            child: Container(
              width: 50,
              height: 40,
              margin: EdgeInsets.only(left: 9),
              child: Icon(
                Icons.visibility,
                color: videoItem.watched ? Colors.red : Colors.white,
              ),
            ),
            onTap: () {
              print("Tap watched $index");
              model.watched(videoItem, !videoItem.watched);
            },
          ),
        ),
        Positioned(
          left: 0,
          right: 0,
          bottom: 40,
          child: Container(
            child: Row(
              children: [
                RatingStarWidget(
                  percentage: (videoData.rating! * 10).toInt(),
                ),
                Container(
                  padding: EdgeInsets.only(top: 4, left: 4),
                  child: Text(
                    "${videoData.rating}",
                    style: TextStyle(
                      color: Colors.white,
                      fontSize: 13,
                      fontWeight: FontWeight.bold,
                    ),
                  ),
                ),
              ],
            ),
          ),
        ),
      ],
    );
  }
}
